package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 认证过滤器
 * @Version: V1.0
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1 判断当前是否是登录请求，如果是登录则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String reqUrl = request.getURI().getPath();
        if (reqUrl.contains("/login/in")) {
            return chain.filter(exchange);
        }

        //2 获取请求头jwt token信息
        String jwtToken = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(jwtToken)){
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3 判断令牌信息是否正确
        try {

            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            //  -1：有效，0：有效，1：过期，2：过期
            int verifyToken = AppJwtUtil.verifyToken(claims);
            //3.1 如果不存在或失效，则拦截
            if (verifyToken > 0) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //3.2 解析JWT令牌信息
            Integer id = claims.get("id", Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());

            //4 将令牌信息传递到各个微服务
            ServerHttpRequest serverHttpRequest = request.mutate().
                    headers( httpHeaders ->{
                        httpHeaders.add("userId", String.valueOf(id));
                    } ).build();
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5 返回结果
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}